const { searchArticle,searchArticleTotal, insertArticle, updateArticle, deleteArticle, publishArticle, findArticle } = require('../service/article.service');
var format = require('date-format');
class ArticleController {
  // 查询文章
  async search(ctx) {
    // 1、接收参数
    const {title, status, sort_id, pageNum, pageSize} = ctx.request.body;
    try {
      const res = await searchArticle({title, status, sort_id, pageNum, pageSize});
      // 查询总数
      const resTotal = await searchArticleTotal({title, status, sort_id});
      let total = resTotal[0].total;

      res.map(item=> {
        item.create_date = format.asString('yyyy-MM-dd hh:mm:ss', item.create_date)
        return item
      })

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {
          result: res,
          total: total
        },
        msg: "查询成功",
      }
    } catch(err) {
      console.log(err)
    }
  }

  // 新增文章
  async add_article(ctx) {
    // 1、接收参数
    const {title, tag_id, sort_id, content, paths} = ctx.request.body;

    try {
      const res = await insertArticle({title, tag_id, sort_id, content, paths});
       // 3、返回数据
      ctx.body = {
        code: 200,
        data: {},
        msg: "新增文章成功",
      }
    } catch(err) {
      console.log(err)
    }
  }
  // 修改文章
  async edit_article(ctx) {
    // 1、接收参数
    const {id, title, tag_id, sort_id, content, paths=''} = ctx.request.body;

    try {
      // 查询文章的paths
      const list = await findArticle({id})
      let newPath = []
      let otherPaths = []
      if(list[0].paths) {
        newPath = JSON.parse(list[0].paths)
      }
      
      if(paths) {
        otherPaths = JSON.parse(paths)
      }
      
      let newPaths = otherPaths.concat(newPath)
      let path = JSON.stringify(newPaths)

      const res = await updateArticle({id, title, tag_id, sort_id, content, path});
       // 3、返回数据
      ctx.body = {
        code: 200,
        data: {},
        msg: "修改文章成功",
      }
    } catch(err) {
      console.log(err)
    }
  }

   // 删除文章
   async del_article(ctx) {
    // 1、接收参数
    const {id} = ctx.request.body;
    try {

      const res = await deleteArticle({id});

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {},
        msg: "删除文章成功",
      }
    } catch(err) {
      console.log(err)
    }
  }
   // 发布文章
   async publish_article(ctx) {
    // 1、接收参数
    const {id, status} = ctx.request.body;
    console.log(id, status)
    try {

      const res = await publishArticle({id, status});

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {},
        msg: "发布文章成功",
      }
    } catch(err) {
      console.log(err)
    }
  }

}

module.exports = new ArticleController()